import 'dart:io';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../theme/kq_theme_manager.dart';
import '../utils/file_util.dart';

class KqGlobal {
  /// 组件库包名，组件库里面的图片引用需要用到这个
  static const String packageName = 'flutter_widgets_pc';

  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  //全局context
  static BuildContext globalContext =
      navigatorKey.currentState!.overlay!.context;

  // 全局 SharedPreferences
  static SharedPreferences? prefs;

  // 初始化SharedPreferences，需要在main.dart中初始化
  static Future init() async {
    try {
      prefs = await SharedPreferences.getInstance();
      // Store a copy of user's preferences on the disk
      if (Platform.isWindows) {
        await _backupPreferences();
      }
    } catch (error) {
      // Remove broken preferences files and restore previous settings
      if (Platform.isWindows) {
        await _restorePreferencesFromBackup();
      }
      prefs = await SharedPreferences.getInstance();
    }
  }

  /// Makes a backup copy of the current shared preferences file.
  static Future<void> _backupPreferences() async {
    try {
      var path = await FileUtil.getRoamingDirectory();

      final String original = '${path}shared_preferences.json';
      final String backup = '${path}shared_preferences_backup.json';

      if (await File(backup).exists()) {
        await File(backup).delete(recursive: true);
      }
      await File(original).copy(backup);
    } catch (_) {
      /* Do nothing */
    }
  }

  /// Removes current version of shared_preferences file and restores previous
  /// user settings from a backup file (if it exists).
  static Future<void> _restorePreferencesFromBackup() async {
    try {
      var path = await FileUtil.getRoamingDirectory();

      final String original = '${path}shared_preferences.json';
      final String backup = '${path}shared_preferences_backup.json';

      await File(original).delete(recursive: true);

      if (await File(backup).exists()) {
        // Check if current backup copy is not broken by looking for letters and "
        // symbol in it to replace it as an original Settings file
        final String preferences = await File(backup).readAsString();
        if (preferences.contains('"') &&
            preferences.contains(RegExp('[A-z]'))) {
          await File(backup).copy(original);
        }
      }
    } catch (_) {
      /* Do nothing */
    }
  }

  /// 当前主题id，如果有多个主题时，切换这个
  static String themeConfigId = kqThemeConfigId;

  /// 图片预览-路由
  static const String routerOfImagePreview = "/ImgPreview";

  /// 文件预览-路由
  static const String routerOfFilePreview = "/FilePreview";
}
